package two_pointer;

import linkedlist.ListNode;

/**
 * Created with IntelliJ IDEA.
 * Description: 19. 删除链表的倒数第 N 个结点
 * User: Li_yizYa
 * Date: 2025/5/12
 * Time: 22:27
 */
public class Solution6 {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null) {
            return null;
        }
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null && n > 0) {
            fast = fast.next;
            n--;
        }
        if (n > 0) {
            return head.next;
        }
        while (fast != null && fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return head;
    }
}
